<template>
	<el-row>
		<div class="div1">
			<span><i class="el-icon-notebook-2"></i> 更改头像</span>
			<hr>
			<div class="img">
				<el-upload class="avatar-uploader" :multipe="false" :show-file-list="true" :auto-upload="false"
					:before-upload="beforeAvatarUpload" :file-list="fileList" :on-change="handleChange"
					action="uploadAction" list-type="picture" accept="image/jpg,image/jpeg">
					<img v-if="imageUrl" :src="imageUrl" class="avatar">
					<span>点击上传图片</span>
				</el-upload>
			</div>
			<div class="btn">
				<el-button type="primary" @click="updatePic()">修改我的图片</el-button>
			</div>
		</div>
	</el-row>
</template>

<script>
	export default {
		name: 'UpdatePic',
		data() {
			return {
				imageUrl: "",
				fileList: []
			}
		},
		methods: {
			handleChange: function(file, fileList) {
				this.fileList = fileList;
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isPNG = file.type === 'image/png';
				const isLt2M = file.size / 1024/ 1024;

				if (!isJPG && !isJPG) {
					this.$message.error('上传图片只能是 JPG 或者是 PNG 格式!');
				}
				if (!isLt2M) {
					this.$message.error('上传图片大小不能超过 1MB!');
				}
				return (isJPG || isPNG) && isLt2M;
			},
			updatePic() {
				let fd = new FormData();
				fd.append("mypic", this.fileList[0].raw);
				this.$postf("/api/user/updatePic", fd).then((resp) => {
					this.$store.state.pic = resp.data.data;
					this.imageUrl=`${this.$ip}/api/public/showimg/${resp.data.data}`;
					this.$message({
						message: '图片上传成功',
						type: 'success'
					});
				})
			}
		},
		mounted() {

		}
	}
</script>

<style scoped>
.div1 span{
	margin-left: 25vw;
}
.div1 hr{
	border: 1px solid #409eff;
}
.div1 .img{
	background-color: #afb7c3;
	width: 500px;
	height: 450px;
}
.div1 .img .el-upload img{
	width: 500px;
	height: 450px;
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.div1 .img .el-upload span{
	width: 100%;
	display: flex;
	position: relative;
	top: 460px;
	right: 470px;
	font-weight: bold;
	font-size: 18px;
}
.div1 .el-button{
	margin-top: 30px;
	margin-left: 600px;
}
</style>